import React, { useState, useCallback, useEffect } from "react"
import { FormProps } from "@/components/modal/form.modal"
import { FormRender, FormUpload } from "@whzhuke/antd"
import { Field_FormSave, Field_name_id } from "@/components/utils/field.list"
import useForm from "antd/es/form/hooks/useForm"
import { Button, Space, Card, Input, Row, Col } from "antd"
import customsService from "@/services/customs.service"
import { functionCommon } from "@whzhuke/common"

interface Props {
  values?: any
  templateId?: string
  templateFile?: string
}

// 固定字段配置（可以根据实际需求调整）
const FIXED_FIELDS = [
  { key: "supplierName", label: "供应商名称", required: true },
  { key: "contractAmount", label: "合同金额", required: true },
  { key: "contractDate", label: "合同日期", required: true },
  { key: "deliveryDate", label: "交货日期", required: false },
  { key: "paymentTerms", label: "付款条件", required: false }
]

export const PreviewContract: React.FC<Props & FormProps> = props => {
  const { values, templateId, templateFile, onDone } = props
  const [form] = useForm<any>()
  const [previewUrl, setPreviewUrl] = useState<string>("")
  const [editingFields, setEditingFields] = useState<Record<string, string>>({})

  // 加载模板文件预览
  useEffect(() => {
    if (templateFile) {
      // 生成预览URL（如果是PDF可以直接预览，Word需要转换）
      const url = functionCommon.replaceHost(templateFile, "public" as any)
      setPreviewUrl(url)
    }
  }, [templateFile])

  // 初始化编辑字段
  useEffect(() => {
    const initialFields: Record<string, string> = {}
    FIXED_FIELDS.forEach(field => {
      if (values?.[field.key]) {
        initialFields[field.key] = values[field.key]
      }
    })
    setEditingFields(initialFields)
    form.setFieldsValue(initialFields)
  }, [values, form])

  // 处理字段修改
  const handleFieldChange = useCallback(
    (key: string, value: string) => {
      setEditingFields(prev => ({
        ...prev,
        [key]: value
      }))
      form.setFieldsValue({ [key]: value })
    },
    [form]
  )

  // 保存合同
  const onFinish = useCallback(
    (data: any) => {
      // 从编辑的字段中提取供应商名称
      const supplierName = editingFields.supplierName || data.supplierName

      const contractData = {
        templateId,
        templateFile,
        contractFile: Array.isArray(data.contractFile) ? data.contractFile[0] : data.contractFile,
        contractName: data.contractName,
        supplierName, // 从固定字段中读取供应商名称
        ...editingFields, // 包含所有固定字段
        ...data
      }

      customsService[values ? "edit" : "save"](contractData)
        .then(res => {
          onDone?.()
        })
        .catch(error => {
          console.error("保存合同失败:", error)
        })
    },
    [values, onDone, templateId, templateFile, editingFields]
  )

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
      {/* 固定字段编辑区域 */}
      <Card title="合同字段编辑" size="small">
        <Row gutter={16}>
          {FIXED_FIELDS.map(field => (
            <Col span={12} key={field.key} style={{ marginBottom: 16 }}>
              <div style={{ marginBottom: 4 }}>
                <span style={{ color: field.required ? "red" : "inherit" }}>*</span>
                {field.label}:
              </div>
              <Input
                value={editingFields[field.key] || ""}
                onChange={e => handleFieldChange(field.key, e.target.value)}
                placeholder={`请输入${field.label}`}
                required={field.required}
              />
            </Col>
          ))}
        </Row>
      </Card>

      {/* 合同预览区域 */}
      <Card title="合同预览" size="small">
        {previewUrl ? (
          <div style={{ width: "100%", height: "600px", border: "1px solid #d9d9d9" }}>
            {previewUrl.endsWith(".pdf") ? (
              <iframe src={previewUrl} style={{ width: "100%", height: "100%", border: "none" }} />
            ) : (
              <div style={{ padding: 20, textAlign: "center" }}>
                <p>文档预览（Word文档需要转换为PDF才能预览）</p>
                <Button type="link" onClick={() => window.open(previewUrl, "_blank")}>
                  在新窗口打开
                </Button>
              </div>
            )}
          </div>
        ) : (
          <div style={{ padding: 40, textAlign: "center", color: "#999" }}>暂无预览内容</div>
        )}
      </Card>

      {/* 表单区域 */}
      <FormRender
        form={form}
        initialValues={
          values
            ? {
                ...values,
                contractFile: values.contractFile ? [values.contractFile] : undefined,
                ...editingFields
              }
            : { ...editingFields }
        }
        layout="horizontal"
        preserve={false}
        onFinish={onFinish}
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 16 }}
        style={{ width: "100%" }}
        fieldList={[
          values ? Field_name_id : undefined,
          {
            fieldType: "input",
            formItemConfig: {
              name: "contractName",
              label: "合同名称",
              required: true,
              rules: [{ required: true, message: "请输入合同名称" }]
            },
            config: {
              placeholder: "请输入合同名称"
            }
          },
          {
            fieldType: "diy",
            formItemConfig: {
              name: "contractFile",
              label: "合同文件",
              required: true,
              rules: [{ required: true, message: "请上传合同文件" }]
            },
            component: <FormUpload maxCount={1} listType="text" allowFile="doc" accept=".pdf,.doc,.docx" />
          },
          { ...Field_FormSave, formItemConfig: { wrapperCol: { offset: 8, span: 16 } } }
        ]}
        autoComplete="off"
      />
    </div>
  )
}
